<template>
  <div>
    <!-- TableModule  tableModule是一个对象，下面有解释 -->
    <TableModule :tableModule="tableModule" ref="TableModuleRef">
      <!-- #event是插入的新增按钮和删除按钮，具体操作按照自己的业务流程实现 -->
      <template #event>
        <el-button type="primary" @click="Add">新增</el-button>
        <el-popconfirm
          :title="`已勾选${multipleSelection.length}条记录，你确定要删除吗?`"
          hide-icon
          confirm-button-type="danger"
          @confirm="Delete"
        >
          <template #reference>
            <el-button type="danger" :disabled="!multipleSelection.length"
              >批量删除</el-button
            >
          </template>
        </el-popconfirm>
        <el-button>
          <el-link
            @click.stop.self
            :underline="false"
            href="https://minio.jiayekj.xyz/sziit-sport-bucket/demo-excel/student-info-demo.xlsx"
            >模板下载</el-link
          >
        </el-button>
        <el-button @click="batchVisible = true">批量添加</el-button>
        <el-button @click="exportExcel()">导出到excel</el-button>
      </template>
      <!-- #tableColumn 插入表格的操作列 -->
      <template #tableColumn>
        <el-table-column align="center" fixed="right" label="操作" width="240">
          <template slot-scope="scope" #default="scope">
            <el-button-group>
              <el-button type="primary" @click="Edit(scope)">编辑</el-button>
              <el-button type="danger" @click="ResetPas(scope)"
                >重置密码</el-button
              >
              <el-popconfirm
                title="你确定要删除这个吗?"
                hide-icon
                confirm-button-type="danger"
                @confirm="DeleteOne(scope)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </el-button-group>
          </template>
        </el-table-column>
      </template>
    </TableModule>
  </div>
  <!-- 单个学生弹窗 -->
  <AddFormModule :addModule="addModule"></AddFormModule>
  <!-- 编辑信息弹窗 -->
  <EditFormModule :editModule="editModule"></EditFormModule>
  <!-- 批量添加 -->
  <el-dialog v-model="batchVisible" title="批量添加" width="500">
    <!-- <el-upload
      class="mx-3"
      :action="actionUrl + '/admin/excel/import/student'"
      :headers="{ Authorization: getToken() }"
      :show-file-list="false"
      accept=".xls,.xlsx"
      :on-success="handleExcelSuccess"
    >
      <el-button>批量添加</el-button>
    </el-upload> -->
    <el-upload
      class="upload-demo"
      :action="actionUrl + '/admin/excel/import/student'"
      :headers="{ Authorization: getToken() }"
      :show-file-list="false"
      accept=".xls,.xlsx"
      :on-success="handleExcelSuccess"
      drag
      multiple
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件放到这里或<em>点击上传</em></div>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import TableModule from "@/components/TableModule.vue";
import AddFormModule from "@/components/AddFormModule.vue";
import EditFormModule from "@/components/EditFormModule.vue";
import { reactive, toRefs, ref, onMounted, toRaw } from "vue";
import { getToken } from "@/utils/auth.js";
import { toast } from "@/utils";
import { columnsData, queryData, addData, editData } from "./table"; // 引入我们配置好的数据
import {
  getAllList,
  addInfo,
  deleteInfo,
  updateInfo,
  resetPasswords,
  getExcel,
} from "@/api/student.js";

const props = defineProps({
  height: Number,
});
const actionUrl = import.meta.env.DEV
  ? "/api"
  : import.meta.env.VITE_APP_BASEURL;
const batchVisible = ref(false);
const state = reactive({
  columns: columnsData, // 表格配置
  query: queryData, // 查询条件配置
  queryForm: {}, // 查询form表单
  editVisible: false, //编辑表单弹窗
  editTitle: "", //编辑表单标题
  edit: editData, //编辑表单配置
  editForm: {}, //编辑form表单
  addVisible: false, //新增表单弹窗
  addTitle: "新增学生", //新增表单标题
  add: addData, //新增表单配置
  addForm: {}, //新增form表单
  loading: false, // 加载状态
  dataList: [], // 列表数据
  multipleSelection: [],
  rowIndex: 0, // 行索引 用于可编辑单元格
  columnIndex: 0, // 列索引 用于可编辑单元格
  height: 0,
  updateImage: {
    row: {},
  },
  pages: {
    isPagination: true,
    // 分页数据
    total: 0,
    limit: 10,
    page: 1,
  },
});

const {
  loading,
  dataList,
  columns,
  pages,
  query,
  queryForm,
  addVisible,
  addTitle,
  add,
  addForm,
  editVisible,
  editTitle,
  edit,
  editForm,
  multipleSelection,
  rowIndex,
  columnIndex,
  height,
  updateImage,
} = toRefs(state);

const TableModuleRef = ref();

onMounted(() => {
  setTimeout(() => {
    state.height = props.height;
  }, 100);
  getDataList();
});

// 传给表格子组件的
const tableModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: getDataList, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  // 以下不说了，上面都给解释了
  queryForm: queryForm,
  columns: columns,
  dataList: dataList,
  multipleSelection: multipleSelection,
  rowIndex: rowIndex,
  columnIndex: columnIndex,
  height: height,
  loading: loading,
  pages: pages,
  query: query,
});

// 传给新增表单子组件的
const addModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: addInfoData, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  // 以下不说了，上面都给解释了
  addForm: addForm,
  addTitle: addTitle,
  add: add,
  addVisible: addVisible,
});

// 传给新增表单子组件的
const editModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: editInfoData, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  // 以下不说了，上面都给解释了
  editForm: editForm,
  editTitle: editTitle,
  edit: edit,
  editVisible: editVisible,
});

// 获取列表信息
async function getDataList() {
  state.loading = true;
  //参数
  let params = {
    pageNum: state.pages.page,
    pageSize: state.pages.limit,
  };
  if (state.queryForm.userId) {
    params.userId = state.queryForm.userId;
  }
  if (state.queryForm.userName) {
    params.userName = state.queryForm.userName;
  }
  // 掉自己的接口，切勿复制粘贴
  const res = await getAllList(params);
  if (res.code == 200) {
    console.log(`output->res`, res);
    toast("获取成功");
    state.dataList = res.data.records;
    state.pages.total = res.data.total;
  } else {
    console.log(`output->error`, res);
    toast(res.msg ? res.msg : "获取失败", "error");
  }
  state.loading = false;
}

// 点击新增触发弹窗
function Add() {
  addVisible.value = true;
  state.addForm = {
    userId: "",
    name: "",
    phone: "",
    classRoom: "",
    educationSystem: "",
    enrollmentYear: "",
    expectedGraduationYear: "",
    employmentDestination: "",
  };
}

//新增信息
async function addInfoData(resImg, file) {
  state.loading = true;
  let data = {
    userId: state.addForm.userId,
    name: state.addForm.name,
  };
  if (resImg) {
    data.avatar = resImg.data.image;
  }
  if (state.addForm.classRoom) {
    data.classRoom = state.addForm.classRoom;
  }
  if (state.addForm.phone) {
    data.phone = state.addForm.phone;
  }
  if (state.addForm.educationSystem) {
    data.educationSystem = state.addForm.educationSystem;
  }
  if (state.addForm.enrollmentYear) {
    data.enrollmentYear = state.addForm.enrollmentYear;
  }
  if (state.addForm.expectedGraduationYear) {
    data.expectedGraduationYear = state.addForm.expectedGraduationYear;
  }
  if (state.addForm.employmentDestination) {
    data.employmentDestination = state.addForm.employmentDestination;
  }
  const res = await addInfo(data);
  if (res.code == 200) {
    console.log(`output->addInfoData`, res);
    toast(res.data ? res.data : "添加失败");
    addVisible.value = false;
    setTimeout(getDataList(), 100);
  } else {
    console.log(`output->addInfoData`, res);
    toast(res.data ? res.data : "添加失败", "error");
  }
  state.loading = false;
}

function Edit(row) {
  // 编辑事件
  // console.log(`output->编辑事件`, toRaw(row.row));
  state.editVisible = true;
  state.editTitle = "修改 " + toRaw(row.row).name + " 的信息";
  state.editForm = {
    userId: toRaw(row.row).userId,
    name: toRaw(row.row).name,
    avatar: toRaw(row.row).avatar
      ? [{ name: toRaw(row.row).name, url: toRaw(row.row).avatar }]
      : [],
    classRoom: toRaw(row.row).classRoom,
    educationSystem: toRaw(row.row).educationSystem,
    enrollmentYear: toRaw(row.row).enrollmentYear,
    expectedGraduationYear: toRaw(row.row).expectedGraduationYear,
    employmentDestination: toRaw(row.row).employmentDestination,
  };
}

//修改信息
async function editInfoData(resImg, file) {
  state.loading = true;
  let data = {
    userId: state.editForm.userId,
    name: state.editForm.name,
    phone: state.editForm.phone,
    classRoom: state.editForm.classRoom,
    educationSystem: state.editForm.educationSystem,
    enrollmentYear: state.editForm.enrollmentYear,
    expectedGraduationYear: state.editForm.expectedGraduationYear,
    employmentDestination: state.editForm.employmentDestination,
  };
  if (resImg) {
    data.avatar = resImg.data.image;
  }
  const res = await updateInfo(data);
  if (res.code == 200) {
    console.log(`output->Edit`, res);
    toast(res.data ? res.data : "修改成功");
    editVisible.value = false;
    setTimeout(getDataList(), 100);
  } else {
    console.log(`output->Edit`, res);
    toast(res.data ? res.data : "修改失败", "error");
  }
  state.loading = false;
}

//重置密码
async function ResetPas(row) {
  state.loading = true;
  let data = {
    userId: toRaw(row.row).userId,
    password: "123456",
  };
  const res = await resetPasswords(data);
  if (res.code == 200) {
    console.log(`output->Edit`, res);
    toast(res.data ? res.data : "修改成功");
  } else {
    console.log(`output->Edit`, res);
    toast(res.data ? res.data : "修改失败", "error");
  }
  state.loading = false;
}

// 单个删除事件
async function DeleteOne(row) {
  state.loading = true;
  // console.log(`output->单个删除事件`, toRaw(row.row));
  const res = await deleteInfo({ userId: toRaw(row.row).userId });
  if (res.code == 200) {
    toast("删除成功");
    setTimeout(getDataList(), 100);
  } else {
    toast("删除失败", "error");
  }
  state.loading = false;
}

// 删除事件
function Delete() {
  state.loading = true;
  let code = true;
  toRaw(state.multipleSelection).forEach(async (item) => {
    const res = await deleteInfo({ userId: item.userId });
    if (res.code != 200) code = false;
  });
  if (code) {
    toast("删除成功");
    setTimeout(getDataList(), 100);
  } else {
    toast("删除失败", "error");
  }
  state.loading = false;
}

function exportExcel() {
  state.loading = true;
  getExcel()
    .then((response) => {
      // console.log(`output->exportExcel`, response);
      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement("a");
      link.href = url;
      let today = new Date();
      let year = today.getFullYear();
      let month = today.getMonth() + 1;
      let day = today.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      let formattedDate = year + "-" + month + "-" + day;
      link.setAttribute("download", `${formattedDate} 学生信息列表.xlsx`); // 这里设置导出的文件名
      document.body.appendChild(link);
      link.click();
      toast(response.data ? response.data : "导出成功");
    })
    .catch((error) => {
      console.error(error); // 如果异步操作失败，则打印错误信息
    });
  state.loading = false;
}

function editInputBlur() {
  console.log("失去焦点回调");
}

//xlsx批量添加
async function handleExcelSuccess(res, file) {
  if (res.code == 200) {
    console.log(`output->handleExcelSuccess`, res);
    toast(res.msg ? res.msg : "添加成功");
    setTimeout(getDataList(), 100);
  } else {
    console.log(`output->handleExcelSuccess`, res);
    toast(res.msg ? res.msg : "添加失败", "error");
  }
  batchVisible.value = false;
}
</script>

<style lang="scss" scoped></style>
